/*
This code is licenced under LGPL v3

Author : Alexandre Stanislawski
*/
/*global window : false, jQuery : false*/
/**
fadeImages

Simple jQuery plugin that can transform a div containing images into a slideshow with a fade as a transition.

In : 
- params : object containing the attributes :  
	- timeout : time before next transition
	- fadeDuration : transition duration
	- initDelay : time before first transition
*/
jQuery.fn.fadeImages = function(params){
    var config = {
        timeout: 4000,
        fadeDuration: 500
    };
    if (params){
        jQuery.extend(config, params);
    }
    if (!config.initDelay){
      config.initDelay=config.timeout;
    }

    function faderCreator(imgSet){
        var current = 0,
          total = imgSet.size(),
          fader = function(){
            var nextIter = current + 1;
            
            if (nextIter >= total){
                nextIter = 0;
            }

            jQuery(imgSet[current]).animate({
                opacity: 0
            }, config.fadeDuration);

            jQuery(imgSet[nextIter]).animate({
                opacity: 1
            }, config.fadeDuration, function(){
                window.setTimeout(fader, config.timeout);
            });

            current = nextIter;
        };
        
        return fader;
    }

    this.each(
    function(){
        var jQthis = jQuery(this),
            imgSet = jQthis.find("img");

        jQthis.css({
            position: "relative",
            overflow: "hidden"
        });

        imgSet.css({
            opacity: 0,
            position: "absolute",
            top: 0,
            left: 0
        });

        imgSet.first().css({
            opacity: 1
        });

        window.setTimeout(faderCreator(imgSet), config.initDelay);
    });
    return this;
};
